<template>
    <div style="padding: 20px;margin-top:20px;margin-bottom: 20px;">
        <page-main title="基础设置">
            <template #title>
                <div class="btn-box">
                    <el-button @click="router.go(-1)">返回</el-button>
                    <el-button type="primary" @click="saveSubmit">保存</el-button>
                </div>
            </template>
            <el-form :model="dataForm" ref="formRef" :inline="false" label-width="140px" :rules="rules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="标准类型" prop="standardTypeCode">
                            <el-select v-model="dataForm.standardTypeCode" clearable style="width:100%"
                                @change="queryShipping(dataForm.standardTypeCode, true)">
                                <el-option v-for="item in TYPE_OPTIONS" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="标准名称" prop="standardName">
                            <el-input v-model="dataForm.standardName" placeholder="请输入名称" clearable style="width:100%"
                                minlength="2" maxlength="20" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关联费用类型" prop="feeTypeDTOList">
                            <el-select v-model="dataForm.feeTypeDTOList" filterable clearable style="width:100%" multiple
                                @change="selectFeeType(dataForm.feeTypeDTOList)" @remove-tag="removeFeeType">
                                <el-option v-for="item in relationOptions" :key="item.typeCode" :label="item.typeName"
                                    :value="item.typeCode" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="同行人标准" prop="companionStandard">
                            <el-select v-model="dataForm.companionStandard" clearable style="width:100%">
                                <el-option v-for="item in TOHORO_OPTIONS" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="超标限制" prop="afterExceed">
                            <el-select v-model="dataForm.afterExceed" clearable style="width:100%">
                                <el-option v-for="item in LIMIT_OPTIONS" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态" prop="enabled">
                            <el-select v-model="dataForm.enabled" clearable style="width:100%">
                                <el-option v-for="item in STATUS_LIST" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="16">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="dataForm.remark" :rows="2" minlength="4" maxlength="500" type="textarea"
                                placeholder="请输入备注" clearable style="width:100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </page-main>
        <page-main title="标准设置">
            <template #title>
                <el-button type="primary" @click="addStandard" :disabled="dataForm.standardTypeCode == ''">新增标准
                </el-button>
            </template>
            <el-table :data="tableData" style="width: 100%" max-height="500px">
                <el-table-column type="index" width="80" label="序号" />
                <el-table-column prop="targetArea" label="适用范围">
                    <template #default="scope">

                        <div class="select-con" @click="selectScope(scope.$index, scope.row)">
                            <p v-if="!scope.row.matchText">请选择适用范围，默认全员适用</p>
                            <div class="scope" v-else>

                                <el-tooltip class="box-item" effect="dark" :content="scope.row.matchText" placement="top">
                                    <p class="scope-area">{{ scope.row.matchText }}</p>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="targetArea" label="适用职级">
                    <template #default="scope">

                        <div class="select-con" @click="selectJobLevel(scope.$index, scope.row)">
                            <p v-if="!scope.row.targetRankText">请选择适用职级，默认全员适用</p>
                            <div class="scope" v-else>
                                <el-tooltip class="box-item" effect="dark" :content="scope.row.targetRankText"
                                    placement="top">
                                    <p class="scope-area">{{ scope.row.targetRankText }}</p>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="address"
                    :label="['airplane', 'train', 'ship'].includes(dataForm.standardTypeCode) ? '城市（目的地）' : '消费城市'">
                    <template #default="scope">
                        <div class="select-con" @click="selectCity(scope.$index, scope.row)">
                            <p v-if="!scope.row.areaText">请选择城市，默认不限</p>
                            <p class="scope" v-else>{{ scope.row.areaText }} </p>
                        </div>
                    </template>
                </el-table-column>

                <template v-if="tableTypeCoulums[dataForm.standardTypeCode]">
                    <!-- 轮船、飞机、火车 -->
                    <el-table-column :label="tableTypeCoulums[dataForm.standardTypeCode].label">

                        <template #default="scope">
                            <el-checkbox-group v-model="scope.row.seatClass"
                                @change="selectCheck(scope.row.seatClass, scope.$index)">
                                <el-checkbox :label="item.configValue"
                                    v-for="(item, index) in tableTypeCoulums[dataForm.standardTypeCode].options"
                                    :key="index">{{ item.configValueName }}</el-checkbox>>
                            </el-checkbox-group>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['customize', 'allowance', 'hotel', 'mileage'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="日期">
                        <template #default="scope">
                            <el-select v-model="scope.row.dateCategoryId" clearable style="width:100%">
                                <el-option v-for="item in dateOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['customize', 'allowance'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="金额（元/天）">
                        <template #default="scope">
                            <el-input v-model="scope.row.amountLimit" placeholder="请输入" clearable min="0.01"
                                max="999999999.99"
                                @input="inputHandle(scope.row.amountLimit, scope.$index, 'amountLimit')" />
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['hotel'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="单人金额（元/天）">
                        <template #default="scope">
                            <div class="flex">
                                <span>&lt;=</span>
                                <el-input v-model="scope.row.singleLimit" placeholder="请输入" clearable min="0.01"
                                    max="999999999.99"
                                    @input="inputHandle(scope.row.singleLimit, scope.$index, 'singleLimit')" />
                                <span class="unit">元</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="双人金额（元/天）">
                        <template #default="scope">
                            <div class="flex">
                                <span>&lt;=</span>
                                <el-input v-model="scope.row.doubleLimit" placeholder="请输入" clearable min="0.01"
                                    max="999999999.99"
                                    @input="inputHandle(scope.row.doubleLimit, scope.$index, 'doubleLimit')" />
                                <span class="unit">元</span>
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="['mileage'].includes(dataForm.standardTypeCode)">
                    <el-table-column label="里程单价">
                        <template #default="scope">
                            <span>&lt;=</span>
                            <el-input v-model="scope.row.amountLimit" placeholder="请输入" clearable min="0.01"
                                style="width:150px" max="999999999.99"
                                @input="inputHandle(scope.row.amountLimit, scope.$index, 'amountLimit')" />
                            <span class="unit">元/公里</span>
                        </template>
                    </el-table-column>
                </template>
                <el-table-column prop="address" label="操作" width="100">
                    <template #default="scope">
                        <el-button link @click="deleteRow(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </page-main>
        <!-- 城市选择 -->
        <citySelectVue :dialogVisible="dialogVisibleCity" @handleClose="handleClose" @on-update="upDateCityInfo"
            :targetArea="targetArea" v-if="dialogVisibleCity"></citySelectVue>
        <!-- 适用范围 -->
        <scopeSelectVue :dialogVisible="dialogVisibleScope" v-if="dialogVisibleScope" :scopeInfo="scopeInfo"
            @handleClose="handleClose" @on-update="upDateScopeInfo">
        </scopeSelectVue>
        <!-- 职级选择 -->
        <JobLevel v-if="targetRankVisible" @handleClose="handleClose" :jobData="jobRowData" @on-update="upDateJobLevelInfo">
        </JobLevel>
    </div>
</template>
<script  setup name="Standard">
import { reactive, watch } from 'vue'
import { STATUS_LIST, TYPE_OPTIONS, LIMIT_OPTIONS, TOHORO_OPTIONS } from '../Common/config'
import { statusText } from '@/util/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { useRoute, useRouter } from 'vue-router'
import citySelectVue from './citySelect.vue'
import scopeSelectVue from './scopeSelect.vue'
import { useUserStore } from '@/store/modules/user'
import JobLevel from '@/components/JobLevel/index.vue'

const dataForm = ref({
    feeTypeDTOList: [],
    companionStandard: 'original',
    standardTypeCode: '',
    standardName: '',
    afterExceed: '',
    enabled: true
})

const targetRankVisible = ref(false)

const router = useRouter()

const route = useRoute()

const tableData = ref([])

const relationOptions = ref([]) // 关联费用类型

const scopeInfo = ref({}) // 适用范围数据

const dateOptions = ref([
    { label: '不限', value: null },

])

const tableTypeCoulums = ref({
    'airplane': { label: '飞机舱位', options: [] },
    'train': { label: '火车坐席', options: [] },
    'ship': { label: '轮船舱位', options: [] },
})

const dialogVisibleCity = ref(false)

const dialogVisibleScope = ref(false)

const formRef = ref(null)

const targetArea = ref('')

const jobRowData = ref('')

const rules = reactive({
    standardTypeCode: [
        {
            required: true,
            message: '请输入',
            trigger: 'blur'
        }
    ],
    standardName: [
        {
            required: true,
            message: '请输入',
            trigger: 'blur'
        },
        {
            max: 20,
            min: 2,
            message: '请输入2-20个字符',
            required: true,

        }
    ],
    remark: [
        {
            max: 500,
            min: 4,
            message: '请输入4-500个字符',
            required: false,

        }
    ],
    feeTypeDTOList: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    companionStandard: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    afterExceed: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    enabled: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ]
})

// 费用标准类型关联费用类型表单的必配组件（最小颗粒度）
const targetCityCodeObj = { code: 'targetCityCode', label: '消费城市' }
const airplaneSeatClassObj = { code: 'airplaneSeatClass', label: '飞机舱位' }
const shipSeatClassObj = { code: 'shipSeatClass', label: '轮船舱位' }
const trainSeatClassObj = { code: 'trainSeatClass', label: '火车坐位' }
const amountObj = { code: 'amount', label: '金额' }
const hotelTypeObj = { code: 'hotelType', label: '房间类型' }
const milesObj = { code: 'miles', label: '里程' }

const budgeTypeListObj = { code: 'budgeTypeList', label: '预算类型及分摊列表' }
const dateObj = [{ code: 'startDate', label: '开始日期' }, { code: 'endDate', label: '结束日期' }]

const arr1 = [targetCityCodeObj, amountObj, budgeTypeListObj]

const arr2 = []

const standardConfig = {
    'airplane': [airplaneSeatClassObj, ...arr1], // 飞机
    'train': [trainSeatClassObj, ...arr1], // 火车
    'ship': [shipSeatClassObj, ...arr1], // 轮船
    'hotel': [...dateObj, hotelTypeObj, ...arr1],// 住宿
    'allowance': [...dateObj, ...arr1],//补贴
    'mileage': [...dateObj, milesObj, ...arr1],// 里程
    'customize': [...dateObj, ...arr1],//其他
}

const formDataSave = ref({})

// 城市范围结构 targetArea="{
// cities:[{code:'11',name:'北京',},{code:'11',name:'北京',}],
//  cityTypes:[{code:'01',name:'一线',},{code:'02',name:'二级',}]
//}"

// 适用范围范围结构 matchTarget="{
//   companies:[{code:'11',name:'公司001',},{code:'11',name:'公司002',}],
//  positions:[{code:'11',name:'岗位001',},{code:'11',name:'岗位002',}],
//  members:[{name:'张三',email:'}]
// }"


const pageType = ref('add')

const tableDataIndex = ref('0')

const userStore = useUserStore()


onMounted(() => {
    const { type, id } = route.query
    pageType.value = type
    getFeeTypeList()
    if (type == 'edit') {
        getDetail(id)
    }
    console.log(userStore)
    userStore.getWorkePosition // 获取岗位
    getDateTypeList()


})


const getDetail = (id) => {
    api.feeConfig.feeStandardDetail({ id }).then(res => {
        // console.log(res)
        try {
            let listFeeType = []
            let obj = { ...res }
            queryShipping(res.standardTypeCode, false)
            res.feeTypeDTOList.forEach(item => {
                listFeeType.push(item.typeCode)
            })
            res.configDTOList.forEach(item => {
                let configContent = item.configContent && JSON.parse(item.configContent)
                item['matchTarget'] = item['matchTarget'] && JSON.parse(item['matchTarget'])
                item['targetArea'] = item['targetArea'] && JSON.parse(item['targetArea'])
                item['targetRank'] = item['targetRank'] && JSON.parse(item['targetRank'])
                item['matchText'] = item['matchTarget']['matchText']
                item['areaText'] = item['targetArea']['areaText']
                item['targetRankText'] = item['targetRank'] && item['targetRank']['targetRankText']
                for (let k in configContent) {
                    item[k] = configContent[k]
                }
            })

            obj['feeTypeDTOList'] = listFeeType
            dataForm.value = obj
            tableData.value = res.configDTOList
            selectFeeType()
        } catch (error) {
            console.log(error, 'error')

        }

    })

}
const inputHandle = (val, index, field) => {
    let regex = /^\d*$/
    if (!regex.test(val)) tableData.value[index][field] = ''

}
// 获取日期类型列表数据
const getDateTypeList = () => {
    const parms = {
        pageNum: 1,
        pageSize: 1000,
    }
    api.feeConfig.dateTypeList(parms).then(res => {
        const { list, total } = res
        list.forEach(item => {
            item['label'] = item.categoryName
            item['value'] = item.id
        })
        dateOptions.value = [...dateOptions.value, ...list]

    })

}


// 获取费用类型对应的表单组件数据
const getFormDetail = (id) => {
    api.feeConfig.formDetail({ id }).then(res => {

        try {
            let formModel = JSON.parse(res.formModel)
            formModel.forEach(item => {
                if (item.fieldName == 'actualReimburseAmount') item.fieldName = 'amount'
                if (item.fieldName == 'budgeRatioTypeList') item.fieldName = 'budgeTypeList'
            })
            formDataSave.value[id] = formModel
        } catch (error) {

        }
    })
}

// 如果选择禁止乘坐则其他选项禁用
const selectCheck = (list, index) => {
    if (list.includes('forbidden')) tableData.value[index]['seatClass'] = ['forbidden']
}

// 获取费用类型
const getFeeTypeList = () => {
    const params = {
        pageNum: 1,
        pageSize: 10000,
        enabled: true
    }
    api.feeConfig.feeTypeList(params).then(res => {
        relationOptions.value = res.list
    })

}

// 新增标准
const addStandard = () => {
    if (tableData.value.length < 50) {
        let obj = { type: dataForm.value.standardTypeCode, targetArea: '', matchTarget: '', dateCategoryId: null, seatClass: [], amountLimit: null, doubleLimit: null, singleLimit: null }
        if (['airplane', 'train', 'ship'].includes(dataForm.value.standardTypeCode)) {
            const optionsList = tableTypeCoulums.value[dataForm.value.standardTypeCode].options
            let result = []
            optionsList.forEach(item => {
                if (item.configValue != 'forbidden') {
                    result.push(item.configValue)
                }
            })
            obj.seatClass = result
        }

        tableData.value.push(obj)
    } else {
        ElMessage.error('最多添加50条标准')
    }


}

// 删除标准
const deleteRow = (index) => {
    tableData.value.splice(index, 1)
}

// 选择范围
const selectScope = (index, row) => {
    tableDataIndex.value = index
    dialogVisibleScope.value = true
    console.log(row.matchTarget, '选择范围')
    scopeInfo.value = row.matchTarget
}

// 选择城市
const selectCity = (index, row) => {
    targetArea.value = row['targetArea'] || ''
    tableDataIndex.value = index
    dialogVisibleCity.value = true

}
// 更新城市信息
const upDateCityInfo = ([obj, text]) => {
    tableData.value[tableDataIndex.value]['targetArea'] = JSON.stringify(obj)
    tableData.value[tableDataIndex.value]['areaText'] = text
}

// 更新范围信息
const upDateScopeInfo = ([obj, text]) => {
    tableData.value[tableDataIndex.value]['matchTarget'] = JSON.stringify(obj)
    tableData.value[tableDataIndex.value]['matchText'] = text
}

//更新职级
const upDateJobLevelInfo = ([obj, text]) => {
    console.log(obj, text)
    tableData.value[tableDataIndex.value]['targetRank'] = JSON.stringify(obj)
    tableData.value[tableDataIndex.value]['targetRankText'] = text
    console.log(tableData.value[tableDataIndex.value])
    handleClose()
}
// 根据费用类型查询
const queryShipping = (val, isAdd) => {
    tableData.value = []
    api.feeConfig.feeStandardTypeQuery({ type: val }).then(res => {
        console.log(res)
        if (res.length > 0) {
            try {
                tableTypeCoulums.value[val]['options'] = res

            } catch (error) {

            }

        }
        if (isAdd) addStandard()
    })

}
// 移除费用类型

const removeFeeType = (val) => {
    let id = statusText(relationOptions.value, val, 'writeFormMetaDataId', 'typeCode')
    delete formDataSave.value[id]
}

// 选择费用类型
const selectFeeType = () => {
    setTimeout(() => {
        dataForm.value.feeTypeDTOList.forEach(item => {
            let id = statusText(relationOptions.value, item, 'writeFormMetaDataId', 'typeCode')
            if (!formDataSave.value[id]) getFormDetail(id)

        })
    }, 500)

}

const selectJobLevel = (index, row) => {
    console.log(row)
    jobRowData.value = row.targetRank || ""
    tableDataIndex.value = index
    targetRankVisible.value = true
}
// 关联的费用类型 飞机 未识别到表单内的 飞机舱位、日期 组件 请先设置好费用类型表单组件后，再尝试关联！


// 标准类型中费用类型是否关联对应的组件
const validateFeeTypeComputend = () => {
    const { standardTypeCode } = dataForm.value
    let list = standardConfig[standardTypeCode]
    let strLable = []
    list.forEach((item) => {
        for (let k in formDataSave.value) {
            let flag = false
            formDataSave.value[k].forEach((fileItem) => {

                if (fileItem.fieldName == item.code) flag = true
            })
            if (!flag) {
                strLable.push(item.label)
            }
            console.log(flag, 8888)

        }
    })

    if (strLable.length > 0) {
        let label = statusText(TYPE_OPTIONS, standardTypeCode)
        let uniqueLable = [...new Set(strLable)]
        ElMessageBox.confirm(`关联的标准类型 ${label} 未识别到表单内 ${uniqueLable} 请先设置好费用类型表单组件后，再尝试关联！?`, "温馨提示", {
            confirmButtonText: "去设置",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            router.push({ name: 'feeType' })
        });
        throw new Error()
    }

}

// 标准类型-标准设置必填项校验
const validateStadardSet = () => {
    let configDTOList = []
    tableData.value.forEach(item => {
        // 飞机、火车、轮船校验
        if (['airplane', 'train', 'ship'].includes(item.type) && item.seatClass.length == 0) {
            ElMessage.error('请选择舱位或座席')
            throw new Error('')
        }
        console.log(item.type, item)
        // 住宿
        if (['hotel'].includes(item.type)) {

            if ([null, ''].includes(item.doubleLimit)) {
                ElMessage.error('请填写双人金额')
                throw new Error('')
            }
            if ([null, ''].includes(item.singleLimit)) {
                ElMessage.error('请填写单人金额')
                throw new Error('')
            }

        }
        // 补贴  // 其他
        if (['allowance', 'customize'].includes(item.type)) {

            if ([null, ''].includes(item.amountLimit)) {
                ElMessage.error('请填写金额')
                throw new Error('')
            }

        }
        // 里程
        if (['mileage'].includes(item.type)) {
            if ([null, ''].includes(item.amountLimit)) {
                ElMessage.error('请填写里程单价')
                throw new Error('')
            }

        }

        if (typeof item['matchTarget'] != 'string') item['matchTarget'] = JSON.stringify(item['matchTarget'])
        if (typeof item['targetArea'] != 'string') item['targetArea'] = JSON.stringify(item['targetArea'])
        if (typeof item['targetRank'] != 'string') item['targetRank'] = JSON.stringify(item['targetRank'])
        let obj = {
            ...item,
            configContent: JSON.stringify({
                type: dataForm.value.standardTypeCode,
                seatClass: item.seatClass || '',
                singleLimit: item.singleLimit || '',
                doubleLimit: item.doubleLimit || '',
                amountLimit: item.amountLimit

            })

        }
        configDTOList.push(obj)

    })
    return configDTOList
}

const saveSubmit = () => {

    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            if (tableData.value.length == 0) return ElMessage.error('请添加标准')
            const configDTOList = validateStadardSet()
            validateFeeTypeComputend()

            const obj = {
                'add': 'feeStandardAdd',
                'edit': 'feeStandardEdit'
            }
            const data = {
                ...dataForm.value,
            }
            data['feeTypeDTOList'] = getRelationOptions()
            data['configDTOList'] = configDTOList
            console.log(data.standardTypeCode)
            data['standardTypeName'] = statusText(TYPE_OPTIONS, data.standardTypeCode)
            console.log(data)
            api.feeConfig[obj[pageType.value]](data).then(res => {
                handleClose()
                router.go(-1)
                ElMessage.success('操作成功')
            })


        } else {
            console.log('error submit!')
            return false
        }
    })
}

// 获取提交的关联类型
const getRelationOptions = () => {
    const { feeTypeDTOList } = dataForm.value
    let list = []
    feeTypeDTOList.forEach(item => {
        relationOptions.value.forEach(item2 => {
            if (item == item2.typeCode) list.push(item2)
        })
    })
    return list
}

const handleClose = () => {
    dialogVisibleCity.value = false
    dialogVisibleScope.value = false
    targetRankVisible.value = false
}

</script>
<style lang="scss" scoped>
.box-item {
    max-width: 70%;
}

.select-con p {
    color: #0049ad;
    cursor: pointer;
}

.flex {
    display: flex;

    span {
        display: inline-block;
        width: 40px;
    }
}

.scope-area {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    width: 300px;
}
</style>
